package com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp30;

import com.alibaba.fastjson.JSON;
import com.caiyi.financial.nirvana.sms.gateway.KeepConnectGateWay;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.CMPPHeader;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.CMPPMessageTool;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.CharsetInfo;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.LongMsgHeader;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp30.message.CMPP3Message;
import com.caiyi.financial.nirvana.sms.gateway.cmpp.cmpp30.message.body.CMPP3Submit;
import com.caiyi.financial.nirvana.sms.queue.SendQueueEntity;
import com.caiyi.financial.nirvana.sms.util.CommUtil;
import com.caiyi.financial.nirvana.sms.util.Constant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class CMPP3Client extends KeepConnectGateWay {

    private static final Logger logger = LoggerFactory.getLogger(CMPP3Client.class);

    public CMPP3Client() {
        super();
    }

    public void start() throws InterruptedException {
        super.start();
        bootstrap.handler(new CMPP3ClientInitializer(this));
    }

    //发送短信
    @Override
    public void sendMessage(SendQueueEntity entity) {
        String json = JSON.toJSONString(entity);
        try {
            //剔除内容签名
            String content = entity.getContent();
            content = content.replaceAll("【.*】", "");
            logger.info("CMPP3Client send : {}", json);
            CMPP3Submit submit = new CMPP3Submit();
            submit.setLevel((byte) 10);
            submit.setSpId(info.getAccount());
            submit.setSrcId(entity.getAccessNumber());
            submit.setDestTerminalId(new String[]{entity.getPhone()});
            submit.setMessageContent(content);
            submit.setMessageFormat(CharsetInfo.UCS2);
            submit.setServiceId("");
            CMPP3Message message = new CMPP3Message();
            CMPPHeader header = new CMPPHeader();
            header.setCommandID(CMPP3Message.CMPP_SUBMIT);
            message.setHeader(header);
            // 长短信内容分割
            List<String> contentChips = CommUtil.splitLongContent(content);
            int sendNum = contentChips.size() > 1 ? contentChips.size() : 1;
            // 长短信设置
            if (sendNum > 1) {
                byte total = (byte) sendNum;
                byte serial = CMPPMessageTool.getOne();
                for (int index = 0; index < contentChips.size(); index++) {
                    CMPP3Message message2 = (CMPP3Message) message.clone();
                    CMPP3Submit submit2 = (CMPP3Submit) submit.clone();
                    LongMsgHeader msgHeader = new LongMsgHeader();
                    // 设置sequenceId对应的发送信息
                    int sequenceId = Constant.seqNo.incrementAndGet();
                    S2M.put(String.valueOf(sequenceId), entity.getMessageId());
                    message2.setSequenceId(sequenceId);
                    msgHeader.setSerial(serial);
                    msgHeader.setTotal(total);
                    msgHeader.setNumber((byte) (index + 1));
                    String contentChip = contentChips.get(index);
                    submit2.setMessageContent(contentChip);
                    submit2.setMsgHeader(msgHeader);
                    submit2.setTpUdhi((byte) 1);
                    submit2.setPkTotal(total);
                    submit2.setPkNumber((byte) (index + 1));
                    message2.setBody(submit2);
                    context.writeAndFlush(message2).addListener((future) -> logger.info("CMPP3Client phone : {}, isDone : {}, isSuccess : {}", entity.getPhone(), future.isDone(), future.isSuccess()));
                }
            } else {
                // 设置sequenceId对应的发送信息
                int sequenceId = Constant.seqNo.incrementAndGet();
                S2M.put(String.valueOf(sequenceId), entity.getMessageId());
                message.setSequenceId(sequenceId);
                message.setBody(submit);
                context.writeAndFlush(message).addListener((future) -> logger.info("CMPP3Client phone : {}, isDone : {}, isSuccess : {}", entity.getPhone(), future.isDone(), future.isSuccess()));
            }
        } catch (Exception e) {
            logger.error("CMPP3Client sendMessage error message : {}", json);
        }
    }

}